<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/11
 * Time: 10:58
 */

namespace app\lib\exception;



use Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    /**
     * @var HTTP 状态码
     */
    private  $code;

    /**
     * @var 错误返回信息
     */
    private  $msg;

    /**
     * @var 自定义错误码
     */
    private $error_code;

    public function render(Exception $exception)
    {
        if ($exception instanceof BaseException){
                //自定义消息，发送给客户端的错误
            $this->code =  $exception->code;
            $this->msg = $exception->msg;
            $this->error_code = $exception->error_code;
        }else{
            //服务器内部错误
            if (config('app_debug')){
                    return parent::render($exception);
            }else{
                $this->code = 500;
                $this->msg = '服务器内部错误';
                $this->error_code = 999;//自定义未知错误
                $this->recordErrorLog($exception);
            }
        }
        $request = Request::instance();//获取request对象
        $result = [
            'msg'=>$this->msg,
            'error_code'=>$this->error_code,
            'request_url'=>$request->url()
        ];
        return json($result,$this->code);
    }
    /**
     * 错误日志记录开关
     * @param Exception $exception
     */
    private  function recordErrorLog(Exception $exception){
        Log::init([
            'type'  => 'File',
            // 日志保存目录
            'path'  => LOG_PATH,
            // 日志记录级别
            'level' => ['error'],
            ]);
        Log::record($exception->getMessage(),'error');
    }
}